import logging
from . import default


class Instance(object):
    def __init__(self, op, op_args=[], op_kwargs={}, name=None, manager=None, info={}):
        '''
        '''
        self.scope = str(default.scope)
        self.name = str(default.scope) + name
        if manager is None:
            self.manager = default.manager
        else:
            self.manager = manager
        self.op = op
        self.op_args = op_args
        self.op_kwargs = op_kwargs
        self.memory_saved = False
        self.info = info

        # if self.save_in_file and self.load_from_file:
        #     logging.warning('Set both save_in_file=True and load_from_file=True is not recommended!')

        '''add to manager'''
        self.manager.add_instance(self)

    def __getattr__(self, key):
        if key == 'df':
            assert self.memory_saved is True, "memory_saved != True"
            assert self in default.session.df_dict, "Can't find value in default session! Use Instance.run() first!"
            return default.session.df_dict[self]
        else:
            raise Exception('Unknown Key: %s' % (key))

    def run(self, sess=None):
        if sess is None:
            sess = default.session
        return sess.run(self)

    def __call__(self, *args, **kwargs):
        return self.run(*args, **kwargs)

    def load(self, sess=None):
        if sess is None:
            sess = default.session
        sess.load_from_file(self)
        return self.df

    def save(self, sess=None):
        if sess is None:
            sess = default.session
        sess.save_to_file(self)
        return True


class LoadInstance(Instance):
    def __init__(self, name, *args, **kwargs):
        kwargs['name'] = name
        super(LoadInstance, self).__init__(None, *args, **kwargs)


class SaveInstance(Instance):
    def __init__(self, data, *args, **kwargs):
        super(SaveInstance, self).__init__(None, *args, **kwargs)
        self.data = data
